package com.example.show_auto.data

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

/**
 * 方案数据模型
 */
data class Scheme(
    val id: String,
    val name: String,
    val combinations: List<SavedCombination>,
    val createTime: Long = System.currentTimeMillis(),
    val userId: String = "" // 用户唯一标识
)

/**
 * 方案存储管理类
 */
class SchemeStorage(private val context: Context) {
    private val prefs: SharedPreferences = context.getSharedPreferences("schemes", Context.MODE_PRIVATE)
    private val gson = Gson()
    private val contextRef = context // 保存context引用，用于动态创建MultiUserDataManager
    
    companion object {
        private const val KEY_SCHEMES = "saved_schemes"
    }
    
    /**
     * 动态获取当前用户ID
     */
    private fun getCurrentUserId(): String? {
        val multiUserDataManager = MultiUserDataManager(contextRef)
        return multiUserDataManager.getCurrentUserId()
    }
    
    /**
     * 保存方案
     */
    fun saveScheme(scheme: Scheme) {
        val currentUserId = getCurrentUserId()
        if (currentUserId == null) return // 如果没有当前用户，不保存
        
        // 为方案添加用户ID
        val schemeWithUserId = scheme.copy(userId = currentUserId)
        
        // 获取所有方案（包括其他用户的）
        val jsonString = prefs.getString(KEY_SCHEMES, null)
        val allSchemes = if (jsonString != null) {
            try {
                val listType = object : TypeToken<List<Scheme>>() {}.type
                gson.fromJson<List<Scheme>>(jsonString, listType) ?: emptyList()
            } catch (e: Exception) {
                emptyList()
            }
        } else {
            emptyList()
        }
        
        // 分离当前用户和其他用户的方案
        val otherUsersSchemes = allSchemes.filter { it.userId != currentUserId }
        val currentUserSchemes = allSchemes.filter { it.userId == currentUserId }.toMutableList()
        
        // 如果已存在同ID方案，替换它；否则添加新方案
        val existingIndex = currentUserSchemes.indexOfFirst { it.id == scheme.id }
        if (existingIndex >= 0) {
            currentUserSchemes[existingIndex] = schemeWithUserId
        } else {
            currentUserSchemes.add(schemeWithUserId)
        }
        
        // 合并所有方案
        val updatedSchemes = otherUsersSchemes + currentUserSchemes
        
        val updatedJsonString = gson.toJson(updatedSchemes)
        prefs.edit().putString(KEY_SCHEMES, updatedJsonString).apply()
    }
    
    /**
     * 获取所有方案
     */
    fun getAllSchemes(): List<Scheme> {
        val currentUserId = getCurrentUserId()
        if (currentUserId == null) return emptyList() // 如果没有当前用户，返回空列表
        
        val jsonString = prefs.getString(KEY_SCHEMES, null) ?: return emptyList()
        return try {
            val listType = object : TypeToken<List<Scheme>>() {}.type
            val allSchemes = gson.fromJson<List<Scheme>>(jsonString, listType) ?: emptyList()
            // 只返回当前用户的方案
            allSchemes.filter { it.userId == currentUserId }
        } catch (e: Exception) {
            emptyList()
        }
    }
    
    /**
     * 删除方案
     */
    fun deleteScheme(schemeId: String) {
        val currentUserId = getCurrentUserId()
        if (currentUserId == null) return // 如果没有当前用户，不执行删除
        
        // 获取所有方案（包括其他用户的）
        val jsonString = prefs.getString(KEY_SCHEMES, null)
        val allSchemes = if (jsonString != null) {
            try {
                val listType = object : TypeToken<List<Scheme>>() {}.type
                gson.fromJson<List<Scheme>>(jsonString, listType) ?: emptyList()
            } catch (e: Exception) {
                emptyList()
            }
        } else {
            emptyList()
        }
        
        // 只删除当前用户的方案
        val updatedSchemes = allSchemes.filter { !(it.userId == currentUserId && it.id == schemeId) }
        
        val updatedJsonString = gson.toJson(updatedSchemes)
        prefs.edit().putString(KEY_SCHEMES, updatedJsonString).apply()
    }
    
    /**
     * 根据ID获取方案
     */
    fun getSchemeById(schemeId: String): Scheme? {
        val currentUserId = getCurrentUserId()
        if (currentUserId == null) return null
        
        return getAllSchemes().find { it.id == schemeId }
    }
    
    /**
     * 检查厨师冲突
     */
    fun checkChefConflicts(targetScheme: Scheme, newCombinations: List<SavedCombination>): List<String> {
        val existingChefs = targetScheme.combinations.flatMap { it.chefs.map { chef -> chef.name } }.toSet()
        val newChefs = newCombinations.flatMap { it.chefs.map { chef -> chef.name } }.toSet()
        
        return existingChefs.intersect(newChefs).toList()
    }
    
    /**
     * 检查地区名冲突
     */
    fun checkAreaConflicts(targetScheme: Scheme, newCombinations: List<SavedCombination>): List<String> {
        val existingAreas = targetScheme.combinations.map { it.areaName }.toSet()
        val newAreas = newCombinations.map { it.areaName }.toSet()
        
        return existingAreas.intersect(newAreas).toList()
    }
    
    /**
     * 更新方案名称
     */
    fun updateSchemeName(schemeId: String, newName: String) {
        val currentUserId = getCurrentUserId()
        if (currentUserId == null) return
        
        // 获取所有方案（包括其他用户的）
        val jsonString = prefs.getString(KEY_SCHEMES, null)
        val allSchemes = if (jsonString != null) {
            try {
                val listType = object : TypeToken<List<Scheme>>() {}.type
                gson.fromJson<List<Scheme>>(jsonString, listType) ?: emptyList()
            } catch (e: Exception) {
                emptyList()
            }
        } else {
            emptyList()
        }
        
        // 只更新当前用户的方案名称
        val updatedSchemes = allSchemes.map { scheme ->
            if (scheme.userId == currentUserId && scheme.id == schemeId) {
                scheme.copy(name = newName)
            } else {
                scheme
            }
        }
        
        val updatedJsonString = gson.toJson(updatedSchemes)
        prefs.edit().putString(KEY_SCHEMES, updatedJsonString).apply()
    }
} 